#!/usr/bin/env python3
#
# Software License Agreement (MIT License)
# Author: Duke Fong <d@d-l.io>

import cgi, sys, os, json, time, filelock
from datetime import datetime
from hashlib import sha1
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from conf.gconf import gconf
from sub import session
from sub import pend
from sub import captcha
from sub.crypt import *
from sub.tpl import *
from sub.helper import *

#data = sys.stdin.read()
data = sys.stdin.read(int(os.environ.get('CONTENT_LENGTH', 0)))

if data:
    class Form(dict):
        pass
    form = Form(json.loads(data))
    form.getvalue = form.get
else:
    form = cgi.FieldStorage()

cmd = form.getvalue('cmd') # login in out out_all, confirm (session)


if cmd == 'confirm':
    print('Content-Type: text/html; charset=utf-8\n')

    todo = pend.get(form.getvalue('pid'))
    if not todo or 'cmd' not in todo:
        print('Error: pid is not valid')
        exit()

    if todo['cmd'] == 'comment':
        article_dir = '../articles/' + todo['url']
        comments_dir = article_dir + '/_comments'
        name = f"{todo['cid']}_email"
        if name not in os.listdir(comments_dir):
            print(f'Error: folder {name} not found')
        os.rename(f'{comments_dir}/{name}', f'{comments_dir}/{todo["cid"]}')
        sid = f'{str(time.time_ns())[:-9]}{random_string()}'
        session.add(todo['email'], sid)
        new_comment_notify(todo['url'], todo['cid'])
        print(comment_verify_ok_tpl({'url': todo['url'], 'cid': todo['cid'], 'sid': sid, 'email': todo['email']}))

    elif todo['cmd'] == 'login':
        sid = f'{str(time.time_ns())[:-9]}{random_string()}'
        session.add(todo['email'], sid)
        print(login_verify_ok_tpl({'url': todo['url'], 'sid': sid, 'email': todo['email']}))


elif cmd == 'login':
    print('Content-Type: application/json; charset=utf-8\n')

    if gconf['comment']['captcha'] == True:
        if not captcha.verify(form.getvalue('captcha_id'), form.getvalue('captcha_code')):
            print('{"error": "Wrong captcha!"}')
            exit(-1)

    url = form.getvalue('url')
    email = form.getvalue('email')
    sid = form.getvalue('sid')
    if sid and session.verify(email, sid):
        print('{"success": "Already logged in.", "refresh": true}')
        exit()

    pid = f'{str(time.monotonic_ns())[:-6]}{random_string()}'
    pend.add({'cmd': 'login', 'url': url, 'email': email}, pid)
    html = login_verify_tpl({'pid': pid, 'admin': gconf['admin']})
    email_to(None, email, "Please verify your login", html)
    print('{"success": "Successed, pending for email verification."}')


else:
    print('Content-Type: application/json; charset=utf-8\n')
    print('{"error": "Unsupported cmd"}')

